/**
 *  对axios进行封装
 */
import axios from 'axios'
import Cookies from 'js-cookie'
import {
    Message
} from 'iview'
import qs from 'qs'
import router from '../router'
// import env from '../../build/env'

// const ajaxUrl = env === 'development' ?
//     'https://sywd11dom.cn/mtz' : ''

//baseURL: "http://127.0.0.1:8080/mtz",
const http = axios.create({

    timeout: 30000,
    headers: {
        'content-type': 'application/x-www-form-urlencoded'
    }
})

// request拦截器
http.interceptors.request.use(req => {
    // http.headers
    var token               = localStorage.getItem("token");
    if  (token) req.headers = {
        'content-type': 'application/x-www-form-urlencoded',
        "token"       : token
    };
    req.data = qs.stringify(req.data)
    return req;
    // var token = Cookies.get('token')
    // if (token) req.data['token'] = token
    // req.data = qs.stringify(req.data)
    // return req
}, error => {
    return Promise.reject(error)
})

// respone拦截器
http.interceptors.response.use(
    response => {

        var result = response.data
        var code   = Number(result.code)
        var msg    = result.msg
        // console.log("response",response);
        if (code < 0) {
            if (code === -1) {
                // 数据异常错误，前台http组件作通用的Message.error处理
                Message.error(msg)
            }
            // 数据异常错误，前台http组件无特殊处理（需要业务层单独处理）
            return Promise.reject(result)
        } else if (code === 0) {
            // 数据正常，前台http组件无特殊处理
            return Promise.resolve(result.data)
        } else {
            Message.warning(msg)
            // 数据异常错误，前台http组件无特殊处理
            return Promise.reject(result)
        }
    },
    error => {
        console.log("status:", error.response.status)
        var status = error.response.status;
        // 判断请求状态为403的话，就弹窗让用户点击确定后进行重新登陆
        if (status == 403) {
            window.location.href = 'http://localhost:8082';
        }

        Message.error(error.message)
        return Promise.reject(error)
    }
)

export default http